import { queryArticles } from '@/services/creationCenter';
import { ArticleSimpleInfo } from '@/services/creationCenter/typing';
import { ProCard, ProFormText, QueryFilter } from '@ant-design/pro-components';
import { Pagination, Tag } from 'antd';
import React, { Suspense, useEffect, useState } from 'react';

const CommentTree = React.lazy(() => import('./CommentTree'));

const pageConfig = {
  page: 1,
  pageSize: 10,
  total: 0,
};
let keywords = '';

const Summarize: React.FC = () => {
  const [articleList, setArticleList] = useState<ArticleSimpleInfo[]>([]);

  async function getArticleList() {
    const res = await queryArticles({
      page: pageConfig.page,
      pageSize: pageConfig.pageSize,
      keywords,
    });
    pageConfig.total = res.data.total;
    setArticleList(res.data.list);
  }

  function pageChange(page: number, pageSize: number) {
    pageConfig.page = page;
    pageConfig.pageSize = pageSize;
    getArticleList();
  }

  function onFilterFinish(queryInfo: { keywords: string }) {
    keywords = queryInfo.keywords;
    getArticleList();
  }

  function resetList() {
    keywords = '';
    pageConfig.page = 1;
    getArticleList();
  }

  useEffect(() => {
    getArticleList();
  }, []);

  return (
    <>
      <QueryFilter
        defaultCollapsed
        onFinish={onFilterFinish}
        onReset={resetList}
      >
        <ProFormText name="keywords" label="标题" />
      </QueryFilter>
      {articleList.map((item) => (
        <ProCard
          style={{ marginBottom: '20px' }}
          key={item.article_id}
          title={
            <span>
              <span style={{ marginRight: '10px' }}>{item.title}</span>
              <Tag color={item.type === 1 ? 'green' : 'cyan'}>
                {item.type === 1 ? '文章' : '随记'}
              </Tag>
            </span>
          }
          bordered
          headerBordered
          collapsible
          defaultCollapsed
        >
          <Suspense>
            <CommentTree articleId={item.article_id} />
          </Suspense>
        </ProCard>
      ))}
      <Pagination
        align="end"
        defaultCurrent={1}
        total={pageConfig.total}
        showQuickJumper
        showSizeChanger={false}
        onChange={pageChange}
      />
    </>
  );
};

export default Summarize;
